def additive_cipher_encrypt(plaintext, key):
    ciphertext = []
    # 确保密钥在0-25范围内
    if not 0 <= key < 26:
        raise ValueError("密钥必须是0-25之间的整数")

    for char in plaintext.upper():
        if char.isalpha():
            # 将字母转换为0-25的数字
            num = ord(char) - ord('A')
            # 加密公式：C = (P + key) mod 26
            encrypted_num = (num + key) % 26
            # 转换回大写字母
            ciphertext.append(chr(encrypted_num + ord('A')))
        else:
            # 非字母字符直接保留
            ciphertext.append(char)
    return ''.join(ciphertext)


def additive_cipher_decrypt(ciphertext, key):
    plaintext = []
    # 确保密钥在0-25范围内
    if not 0 <= key < 26:
        raise ValueError("密钥必须是0-25之间的整数")

    for char in ciphertext.upper():
        if char.isalpha():
            num = ord(char) - ord('A')
            # 解密公式：P = (C - key) mod 26
            decrypted_num = (num - key) % 26
            plaintext.append(chr(decrypted_num + ord('A')))
        else:
            plaintext.append(char)
    return ''.join(plaintext)


# 使用示例
if __name__ == "__main__":
    key = 3  # 凯撒密码经典位移值（0-25）
    plaintext = "HELLOWORLD"

    encrypted = additive_cipher_encrypt(plaintext, key)
    print(f"加密结果: {encrypted}")  # 输出：KHOORZRUOG

    decrypted = additive_cipher_decrypt(encrypted, key)
    print(f"解密结果: {decrypted}")  # 输出：HELLOWORLD